//
//  View3CollectionLayout.swift
//  ChapterAll
//
//  Created by Kevin on 2020/4/23.
//  Copyright © 2020 Kevin. All rights reserved.
//

import UIKit

class View3CollectionLayout: UICollectionViewFlowLayout {
    
    var itemCount:Int?
    var attrs:Array<UICollectionViewLayoutAttributes>?
    
    override func prepare() {
        super.prepare()
        
        attrs = Array<UICollectionViewLayoutAttributes>()
        // 条目个数
        itemCount = collectionView?.numberOfItems(inSection: 0)
        // 大圆直径
        let radius = min(collectionView!.frame.width, collectionView!.frame.height) / 2
        // 圆心位置
        let center = CGPoint(x: collectionView!.frame.width / 2, y: collectionView!.frame.height / 2)
        // 获取全部条目
        for i in 0..<itemCount! {
            let attr = UICollectionViewLayoutAttributes(forCellWith: IndexPath(item: i, section: 0))
            // 条目大小
            attr.size = CGSize(width: 50, height: 50)
            // 圆心位置
            let p = CGFloat(2 * Double.pi) / CGFloat(itemCount!) * CGFloat(i)
            let x = CGFloat(center.x) + cos(p) * (radius - 25)
            let y = CGFloat(center.y) + sin(p) * (radius - 25)
            attr.center = CGPoint(x: x, y: y)
            
            attrs?.append(attr)
        }
    }
    
    override var collectionViewContentSize: CGSize {
        return collectionView!.frame.size
    }
    
    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        return attrs!
    }
}
